package com.crpc.core.compress.impl;

import com.crpc.common.crpcEnum.CrpcExceptionEnums;
import com.crpc.common.exception.CrpcException;
import com.crpc.core.compress.Compressor;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;


/**
 * @author wzy
 * @version 1.0
 * @description:
 * @date 2023/9/30 9:09
 */
@Slf4j
public class GzipCompressor implements Compressor {
    @Override
    public byte[] compress(byte[] bytes) {

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream)) {
            gzipOutputStream.write(bytes);
            log.info("===============使用Gzip进行压缩===============");
        } catch (IOException e) {
            log.error("===============压缩时发生异常===============");
            e.printStackTrace();
            throw new CrpcException(CrpcExceptionEnums.COMPRESS_ERROR);
        }
        return outputStream.toByteArray();
    }

    @Override
    public byte[] decompress(byte[] bytes) {
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try (
                GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream);
        ) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = gzipInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            log.info("===============使用Gzip进行解压缩===============");
            return outputStream.toByteArray();

        } catch (Exception e) {
            log.error("===============解压缩时发生异常===============");
            e.printStackTrace();
            throw new CrpcException(CrpcExceptionEnums.COMPRESS_ERROR);
        }
    }
}
